const { Random } = require('mockjs')
import { MockMethod } from 'vite-plugin-mock'
const tokens: any = {
  admin: `admin-token-${Random.guid()}-${new Date().getTime()}`,
  editor: `editor-token-${Random.guid()}-${new Date().getTime()}`,
  test: `test-token-${Random.guid()}-${new Date().getTime()}`,
}
const username2role: any = {
  admin: ['Admin'],
  editor: ['Editor'],
  test: ['Admin', 'Editor'],
}
const role2permission: any = {
  Admin: ['read:system', 'write:system', 'delete:system'],
  Editor: ['read:system', 'write:system'],
  Test: ['read:system'],
}
export default [
  {
    url: '/system/login',
    timeout: 200,
    method: 'POST',
    response: ({ body }: any) => {
      const { username } = body
      const token = tokens[username]
      if (!token)
        return {
          code: 500,
          msg: '帐户或密码不正确',
        }
      return {
        code: 200,
        msg: 'success',
        data: { token },
      }
    },
  },
  {
    url: '/system/logout',
    timeout: 200,
    method: 'get',
    response() {
      return {
        code: 200,
        msg: 'success',
      }
    },
  },
  {
    url: '/system/user/getUserInfo',
    method: 'get',
    response: (config: any) => {
      const authorization = config.headers.authorization || config.headers.Authorization
      if (!authorization.startsWith('Bearer '))
        return {
          code: 401,
          msg: '令牌无效',
        }
      const username = authorization.replace('Bearer ', '').split('-token-')[0]
      const roles = username2role[username] || []
      const permissions = [...new Set(roles.flatMap((role: any) => role2permission[role]))]
      return {
        code: 200,
        msg: 'success',
        data: {
          username,
          roles,
          permissions,
          avatar: 'https://p3-passport.byteacctimg.com/img/user-avatar/44534828b73a60680508a3de7a8750d2~300x300.image',
        },
      }
    },
  },
] as MockMethod[]
